package com.ying.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * ClassName: RabbitMQUtils
 * Package: com.ying.util
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/3/23 20:08
 * @Version 1.0
 */
public class RabbitMQUtils {
    /*获取连接*/
    public static Connection getConnection(String host,int port,String virtualHost,String username,String password) {//import com.rabbitmq.client.Connection;
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost(virtualHost);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);

        try {
            return connectionFactory.newConnection();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*释放资源*/
    public static void release(Connection conn, Channel channel) {
        if (channel!=null) {
            try {
                channel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (conn!=null) {
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
